#include "stm32f10x.h"
#include <string.h>
#include "freertos.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
#include "UART1.h"
#include "LED.h"
#include "DELAY.h"
#include "OLED.h"
#include "ADC.h"
#include "Flash.h"
#include "stm32f10x_wwdg.h"
#include "My_WWDG.h"
#include "My_SPI.h"
#include "Key.h"
#include "PWM.h"

int FLAG = 0;
int WifiConnect_Flag = 0;
int BlueTooth_Flag = 1;
char g_Buf[100] = {0};
TaskHandle_t hand1;
QueueHandle_t	queue, queue2, queue3;
int flag_connect = 0;

void wait_Certain(uint16_t wait_Time);
void wait(void);
int judge(void);
void connect_WIFI(void);
void Deal_SensorData(void);
void connect_Server(void);
void TCP_Connect(void);
void SendData_Connect(char *buf);
void Close_Conncet(void);

/* 使用时钟节拍延时	*/
void wait_Certain(uint16_t wait_Time) {
    uint16_t now_time = xTaskGetTickCount();
    uint16_t target_time = now_time + wait_Time;

    while (now_time < target_time) {
        now_time = xTaskGetTickCount();
    }
}


void wait(void) {
    int i = 0;

    while (i < 37000000) {
        i++;
    }

    return;
}

int judge(void) {

	wait();
    if (strstr(g_Buf, "OK")) {
        memset(g_Buf, 0, sizeof(g_Buf));
        Turn_On_LED_A1();
        Delay_ms(500);
        Turn_Off_LED_A1();
        FLAG = 1;

        BlueTooth_Flag = 0;
        wait_Certain(5000);
        return 0;
    }

    if (strstr(g_Buf, "ERROR")) {
        memset(g_Buf, 0, sizeof(g_Buf));
        wait_Certain(5000);
        return 1;
    }

    if (strstr(g_Buf, "FAIL")) {
        memset(g_Buf, 0, sizeof(g_Buf));
        wait_Certain(5000);
        return 1;
    }

    wait_Certain(5000);
    return 1;
}

int judge_WifiConnect(void) {
	connect_WIFI();
	wait();
    printf2("AT+CWJAP_DEF?\r\n");
	printf3("----Judge WIFI ----\r\n");
    wait();

	if (strstr(g_Buf, "No")!=NULL) {
        memset(g_Buf, 0, sizeof(g_Buf));
        Turn_On_LED_A1();
        Delay_ms(500);
        Turn_Off_LED_A1();
        WifiConnect_Flag = 0;
        printf3("----No WIFI----\r\n");
		return 1;
		
    }

	
    if (strstr(g_Buf, "+CWJAP_DEF:")!=NULL) {
        memset(g_Buf, 0, sizeof(g_Buf));
        Turn_On_LED_A1();
        Delay_ms(500);
        Turn_Off_LED_A1();
        WifiConnect_Flag = 1;
		printf3("------Yes WIFI------\r\n");
        return 0;
    } else {
        memset(g_Buf, 0, sizeof(g_Buf));
        Turn_On_LED_A1();
        Delay_ms(500);
        Turn_Off_LED_A1();
        WifiConnect_Flag = 0;
		printf3("------No Answer ------\r\n");
        return 1;
    }
}

void connect_WIFI(void) {
    printf3("need connect\r\n");
    int times = 0;
    char buf[50] = {0};
    char buf1[25] = {0};
    char buf2[25] = {0};

    int Wifi_Info = 0;
    int time = 0;
    int timeout = 10000;

    // -------------接收账号密码------------
    while (1) {
        char ch = 0;
        BaseType_t ret = xQueueReceive(queue, &ch, 1);

        //		OLED_ShowString(2,1,buf);
        //判断队列是否接收完成蓝牙传来的名字和密码!...=...!
        if (ret == pdTRUE) {
            buf[strlen(buf)] = ch;

            if (ch == '!') {
                times ++;
            }

            if (times == 2) {
                //				OLED_ShowString(2,1,buf);
                Wifi_Info = 1;
                break;
            }

        }

        time++;


        //WIFI_INFO是0 没有从蓝牙获得联网信息
        //如果超过十秒没有WIFI信息，那么去FLASH找
        if (time > timeout) {


            int address = 0x0800F000;
            int status = 0;
            char buffer[40] = {0};
			buffer[strlen(buffer)]='\0';
            status = *((__IO uint32_t *)(address));

            if (status != 0xFFFFFFFF) {
                // 有内容

                readFlash(address+8, buffer, 40);
                sscanf(buffer, "%[^=]=%s", buf1, buf2);
				
                printf3("Connet By FLASH!!\r\n");
				printf3("UserName: %s PWD : %s \r\n",buf1,buf2);
                break;
            } else {
                // Flash无内容, 存入数据
                printf3("Connect Fail\r\n");
                break;
            }
        }

    }

    // ---------------收完账号密码： 切割----------------


    if (Wifi_Info) {
        for (int i = 1; i < 50 ; i++) {
            if (buf[i] != '=') { //拆分名字字符串
                buf1[i - 1] = buf[i];
            }

            if (buf[i] == '=') { //拆分密码字符串
                int j = i + 1;
                int idx = 0;

                for (; j < strlen(buf) -1; j++) {
                    buf2[idx] = buf[j];
                    idx++;
                }

            }
        }
    }


    printf3("connect success\r\n");

    printf3("WIFI Flag: %d\r\n", Wifi_Info);

    if (Wifi_Info == 1) {
        /*如果是蓝牙传送的WIFI信息，则写入Flash	*/
        int address = 0x0800F000;

        char buffer[40] = {0};

        sprintf(buffer, "%s=%s", buf1, buf2);

        buffer[strlen(buffer)] = '\0';
        erasePage(address);

        changeFlashFor32(address, 14);
        changeFlashFor32(address + 4, strlen(buffer));

        for (int i = 0; i < sizeof(buffer); i += 4) {
            changeFlashFor32(address + 8 + i, *(int *)(buffer + i));
        }

        printf3("Writing Done: \r\n");
    }


	printf2("AT+CWJAP_DEF=\"%s\",\"%s\"\r\n", buf1, buf2); //打印回传蓝牙


    memset(buf, 0, strlen(buf));//释放buf内存空间
    memset(buf1, 0, strlen(buf1));//释放buf内存空间
    memset(buf2, 0, strlen(buf2));//释放buf内存空间

    wait();
}



void Deal_SensorData(void) {
    wait_Certain(1000);
    connect_WIFI();

    int count = 0;


    //连三次都失败
    while (1) {
			memset(g_Buf,0,strlen(g_Buf));
		 if (!judge_WifiConnect()) {

            printf3("WIFI CONNCET! \r\n");
            count = 0;

			char sensorData_ForW25Q64[100] = {0};
            getMSG(sensorData_ForW25Q64);
			int lenth=strlen(sensorData_ForW25Q64);
			int base_address = 0x000000;
				
			uint8_t Read_FLAG=W25Q64_Read_Byte(base_address);
			
			char buffer[40] = {0}; 
			printf3("Reading......\r\n");
			TCP_Connect();
			while(Read_FLAG!=0xFF){
				memset(buffer,0,strlen(buffer));
				for (int i=0; i <lenth; i++) {
				buffer[i]=W25Q64_Read_Byte(base_address+i);
				}
				buffer[strlen(buffer)]='\0';
				base_address+=strlen(sensorData_ForW25Q64);
				
				char FormatData[50]={0};
				sscanf(buffer,"+%[^+]",FormatData);
				Read_FLAG=W25Q64_Read_Byte(base_address);

				SendData_Connect(FormatData);
				printf3("waiting......\r\n");
				wait();
			}
			Close_Conncet();
			
			printf3("Start Erasing\r\n");
            W25Q64_Erase_Sector(0x000000); // 擦除扇区0
            W25Q64_Erase_Sector(0x001000);// 擦除扇区1
            W25Q64_Erase_Sector(0x002000);// 擦除扇区2
			printf3("Erase Done\r\n");
			
			printf3("Outline Data Read Done\r\n");
			int nowDataTimes=0;
			while(nowDataTimes<10){
			
			connect_Server();
			wait_Certain(6000);
			nowDataTimes++;
			}
			wait_Certain(2000);
        }
		
		
		count++;
		printf3("count: %d\r\n",count);
        if (count == 3) {

            int base_address = 0x000000;
            int keep = 0;
			printf3("Start Erasing\r\n");
            W25Q64_Erase_Sector(0x000000); // 擦除扇区0
            //W25Q64_Erase_Sector(0x001000);// 擦除扇区1
            //W25Q64_Erase_Sector(0x002000);// 擦除扇区2
			printf3("Erase Done\r\n");
            while ((keep = judge_WifiConnect()) == 1) {	
                char sensorData[40] = {0};
                char write_Data[50]={0};
				getMSG(sensorData);				
				sprintf(write_Data,"%s",sensorData);
				printf3("Write_Data: %s\r\n",write_Data);
                W25Q64_Write_String(base_address,write_Data);
                base_address += strlen(write_Data);
                printf3("OutLine Sensor \r\n");
                wait();
            }
            printf3("out of template: %d \r\n", keep);
        }

    }
}

void connect_Server(void) {
	
    printf2("AT+CIPSTART=\"TCP\",\"47.115.220.165\",9037\r\n");

    if(judge())
		return;


    printf2("AT+CIPMODE=1\r\n");

    while (judge());

    printf2("AT+CIPSEND\r\n");


    //if W25Q64 have data
    //send data and erase

    char sensorData[100] = {0};
    getMSG(sensorData);


    char realData[200] = {0};
    sprintf(realData, "POST /0 HTTP/1.1\r\n\r\n%s", sensorData);


	if(judge())
		 return ;

    //   printf2(sensorData);

    printf2("%s", realData);




    wait();
    printf2("+++");

    wait();
    printf2("AT+CIPMODE=0\r\n");

    while (judge());

    printf2("AT+CIPCLOSE\r\n");


}


void TCP_Connect(void){
    wait();
	printf2("AT+CIPSTART=\"TCP\",\"47.115.220.165\",9037\r\n");

    while (judge());


    printf2("AT+CIPMODE=1\r\n");

    while (judge());

    printf2("AT+CIPSEND\r\n");

}


void SendData_Connect(char *buf){
	char realData[200] = {0};
	char template_Data[100]={0};
	sprintf(template_Data,"%s",buf);
    sprintf(realData, "POST /0 HTTP/1.1\r\n\r\n%s", template_Data);


    if(judge())
		 return ;

    //   printf2(sensorData);

    printf2("%s", realData);




    wait_Certain(2000);
}

void Close_Conncet(void){
	wait();
	printf2("+++");

    wait();
    printf2("AT+CIPMODE=0\r\n");

    if(judge())
		 return ;

    printf2("AT+CIPCLOSE\r\n");
}





void task1(void * arg) {

    Deal_SensorData();
    connect_Server();

    while (1) {


    }
}


void task2(void * arg) {
    char buf_esp[50] = {0};

    while (1) {

        char ch = 0;
        BaseType_t ret = xQueueReceive(queue2, &ch, 0);

        if (ret == pdTRUE) {
            buf_esp[strlen(buf_esp)] = ch;
            g_Buf[strlen(g_Buf)] = ch;
			g_Buf[strlen(g_Buf)]='\0';
            printf3("%c", ch);
        }


        memset(buf_esp, 0, sizeof(buf_esp));
    }
}

void task3(void *arg){
		uint8_t Brightness;
	  while (1) {
        for (Brightness = 0; Brightness <= 100; Brightness++) {
            PWM_SetComparel(Brightness);
            Delay_ms(10);
        }

        for (Brightness = 0; Brightness <= 100; Brightness++) {
            PWM_SetComparel(100 - Brightness);
            Delay_ms(10);
        }
    }
}

int main(void) {
    //OLED_Init();

	PWM_Init();
    KEYInit();
    LED_Init();
    AD_Init();
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);

    //窗口看门狗暂未使用
    //KEYInit();
    USART1_Init();
    USART2_Init();
    USART3_Init();
    Delay_Init();
    SPI1_Init();


    queue = xQueueCreate(40, 1);
    queue2 = xQueueCreate(40, 1);
    queue3 = xQueueCreate(40, 1);
    xTaskCreate(task1, "Task1", configMINIMAL_STACK_SIZE * 4, NULL, tskIDLE_PRIORITY + 1, &hand1);
    xTaskCreate(task2, "Task2", configMINIMAL_STACK_SIZE*4, NULL, tskIDLE_PRIORITY + 1, NULL);
	xTaskCreate(task3, "Task3", configMINIMAL_STACK_SIZE*4, NULL, tskIDLE_PRIORITY + 1, NULL);
    vTaskStartScheduler();

    while (1) {
    }
}
